import { defineComponent, ref, watch, PropType, VNode } from "vue";
import { Delete, Search, CirclePlus, Edit } from "@element-plus/icons-vue";
import type { RenderContentFunction, TreeInstance, FilterNodeMethodFunction } from "element-plus";
import { ElButton, ElIcon, ElTooltip } from "element-plus";
import { ElInput, ElScrollbar, ElTree } from "element-plus";
import "./basic-header.scss";

interface Props {
  treeData?: any[];
  defaultProps?: {
    children?: string;
    label?: string;
  };
  placeholderTree?: string;
  tableKey?: string | number;
  buttonInfo?: {
    name?: string
  },
  treeButtonInfo?: {
    add?: Boolean
    remove?: Boolean
    edit?: Boolean
  }
}

type Emits = {
  (e: "nodeClick", node: any): void;
  (e: "refresh"): void;
};

const BasicLayout = defineComponent({
  name: "BasicLayoutHeader",
  props: {
    treeData: {
      type: Array as PropType<any[]>,
      default: () => []
    },
    defaultProps: {
      type: Object as PropType<{
        children?: string;
        label?: string;
      }>,
      default: () => ({
        children: 'children',
        label: 'label'
      })
    },
    placeholderTree: {
      type: String as PropType<string>,
      default: "请输入"
    },
    tableKey: {
      type: [String, Number] as PropType<string | number>,
      default: "0"
    },
    buttonInfo: {
      name: String
    },
    treeButtonInfo: {
      add: Boolean,
      remove: Boolean,
      edit: Boolean
    }
  },
  emits: ["nodeClick", "refresh"] as unknown as Emits,
  setup(props, { slots, emit }) {
    const filterText = ref("");
    const treeRef = ref<TreeInstance | null>(null);

    // 修复1：明确过滤方法的类型和实现
    const filterNode: FilterNodeMethodFunction = (value: string, data: any) => {
      if (!value) return true;
      // 修复2：确保label字段正确（使用props中定义的label字段名）
      const labelField = props.defaultProps?.label || 'label';
      return data[labelField]?.includes(value) || false;
    };

    // 修复3：添加防抖和存在性检查
    watch(filterText, (val) => {
      if (treeRef.value) {
        // 延迟执行，避免输入过快导致的性能问题
        setTimeout(() => {
          treeRef.value!.filter(val);
        }, 100);
      }
    });

    const handleNodeClick = (node: any) => {
      emit("nodeClick", node);
    };

    const handleRefresh = () => {
      emit("refresh");
    };
    // 自定义树节点渲染函数
    const renderContent: RenderContentFunction = (h, { node, data }) => {
      const addButton = props.treeButtonInfo?.add
        ? <ElIcon
          class="icon-plus "
          onClick={(e) => {
            e.stopPropagation();
            emit("add-node", data);
          }}
        >
          <CirclePlus />
        </ElIcon>
        : null;
      const editButton = props.treeButtonInfo?.edit
        ? <ElIcon
          class="icon-plus "
          onClick={(e) => {
            e.stopPropagation();
            emit("edit-node", data);
          }}
        >
          <Edit />
        </ElIcon>
        : null;
      const removeButton = props.treeButtonInfo?.remove
        ? <ElIcon
          class="icon delete-icon"
          onClick={(e) => {
            e.stopPropagation();
            emit("delete-node", data);
          }}
        >
          <Delete />
        </ElIcon>
        : null;
      return (
        <div class="custom-tree-node">
          <span class="label">{node.label}</span>
          <div class="actions">
            {addButton}
            {editButton}
            {removeButton}

            {/* <ElTooltip content="删除节点" placement="top">
              <ElIcon
                class="icon delete-icon"
                onClick={(e) => {
                  e.stopPropagation();
                  emit("delete-node", data);
                }}
              >
                <Delete />
              </ElIcon>
            </ElTooltip> */}
          </div>
        </div>
      );
    };
    return () => {
      const renderTopContent = (): VNode => {
        return (
          <div class="layout-header">
            {slots.header && (
              <div class="header-layout-header">
                {slots.header()}
              </div>
            )}
          </div>
        );
      };
      const renderTopTab = (): VNode => {
        return (
          <div class="layout-tab">
            {slots.tab && (
              <div class="header-layout-tab">
                {slots.tab()}
              </div>
            )}
          </div>
        );
      };
      const renderLeftTree = (): VNode => {
        if (slots.tree) {
          return (
            <div class="header-layout-left">
              {slots.tree()}
            </div>
          );
        }

        if (props.treeData?.length) {
          return (
            <div class="header-layout-left">
              <ElInput
                placeholder={props.placeholderTree}
                clearable
                suffix-icon={Search}
                // 正确的v-model绑定方式：使用modelValue和onUpdate:modelValue
                modelValue={filterText.value}
                onUpdate:modelValue={(val) => {
                  filterText.value = val;
                }}
                // 清空逻辑
                onClear={() => {
                  filterText.value = '';
                  treeRef.value?.filter('');
                }}
              />

              <ElScrollbar>
                <ElTree
                  ref={treeRef}
                  // 修复5：确保过滤方法正确绑定
                  filter-node-method={filterNode}
                  style={{ maxWidth: "600px" }}
                  data={props.treeData}
                  props={props.defaultProps}
                  onNodeClick={handleNodeClick}
                  // 修复6：添加必要的配置项
                  default-expand-all
                  show-checkbox={false}
                  render-content={renderContent}
                />
              </ElScrollbar>
            </div>
          );
        }

        return <div class="header-layout-left"></div>;
      };

      const renderRightContent = (): VNode => {
        return (
          <div class="header-layout-right">
            {slots.search && (
              <div class="header-layout-right-search">
                {slots.search()}
              </div>
            )}

            {slots.tableContent && (
              <div class="header-layout-right-table">
                {slots.tableContent()}
              </div>
            )}
          </div>
        );
      };

      return (
        <div class="layout">
          {renderTopContent()}
          <div class="header-content">
            {renderTopTab()}
            <div class="header-layout">
              {renderLeftTree()}
              {renderRightContent()}
            </div>
          </div>
        </div>

      );
    };
  }
});

export default BasicLayout;
